/*
 * ============================================================================
 *
 *       Filename:  itimer.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2014年03月19日 15时50分20秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <pthread.h>
#include <sys/time.h>
#include <string.h>
#include <signal.h>
#include <errno.h>

struct itimerval itv;

void *print_expire(void *arg)
{
	int ret;
	while(1) {
		ret = getitimer(ITIMER_PROF, &itv);
		if(ret != 0)
			perror(strerror(errno));
//		printf("left:%d\n", itv.it_value.tv_sec);
		sleep(1);
	}
}


void timer(int arg)
{
	static int i = 0;
	switch(arg) {
	case SIGPROF:
		printf("signal:%s, time:%d\n", "SIGPROF", i++);
		fflush(stdout);
	}
}

void *killsignal(void *sigp)
{
	int i;
	for(i = 0; i < 10; i++){
		kill(getpid(), *(int *)sigp);
	}
}

int main()
{	
	struct sigaction sigprof_act;
	sigprof_act.sa_handler = timer;
	sigemptyset(&sigprof_act.sa_mask);
//	sigaddset(&sigprof_act.sa_mask, SIGPROF);
	sigprof_act.sa_flags = 0;
	sigaction(SIGPROF, &sigprof_act, NULL);

	struct timeval interval = {.tv_sec = 5, .tv_usec = 0};
	struct timeval expire = {.tv_sec= 3, .tv_usec = 0};
	itv.it_interval = interval;
	itv.it_value = expire;
	
	pthread_attr_t pid_attr;
	pthread_attr_init(&pid_attr);
	pthread_attr_setdetachstate(&pid_attr, PTHREAD_CREATE_DETACHED);

	pthread_t pid;
	//pthread_create(&pid, &pid_attr, print_expire, NULL);

	int sig = SIGPROF;
	pthread_create(&pid, &pid_attr, killsignal, &sig);
	//setitimer(ITIMER_PROF, &itv, NULL);
	while(1);
}
